/**
 * 不完整管道的读示例
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{

    int pipe_fds[2];
    if (pipe(pipe_fds) < 0)
    {
        perror("pipe error: ");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if (0 > pid)
    {
        perror("fork error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == pid)
    {
        close(pipe_fds[0]);

        char *str = "12345";
        write(pipe_fds[1], str, strlen(str));

        close(pipe_fds[1]);
    }
    else
    {
        close(pipe_fds[1]);
        sleep(5); // 睡眠，保证子进程先执行，写入数据到管道后，关闭管道

        char c;
        while (read(pipe_fds[0], &c, 1))
        {
            printf("%c", c);
        }
        printf("\n");

        close(pipe_fds[0]);

        wait(0);
    }
    return 0;
}